import React, {Component} from 'react'
import {
    Text,
    View,
    StyleSheet,
    Button,
    Image,
    FlatList,
    ScrollView,
    TextInput,
    TouchableOpacity,
    Alert, AlertIOS
} from 'react-native'
import {padding, default as styles, rectWithSize, HUNDRED_PERCENT, margin} from "../../style";
import Stepper from "../../component/widget/Stepper";
import CommonRadio from "../../component/common/CommonRadio";
import {AppIcon} from "../../assets/icon/AppIcon";
import {Actions} from "react-native-router-flux";
import toast from "../../component/common/ToastProxy";
import {AlertButtonStyle, alertProxy, AlertProxyBtn} from "../../component/common/AlertProxy";
import {inject, observer} from "mobx-react/custom";
import {
    ProductModelExtraInfoInterface,
    ProductModelInterface,
    ProductSpecificationInterface
} from "../../net/instance/CommenModelInstance";
import {afterAnimation, defaultObj, getAssetUrl, toFixed} from "../../util";
import FastImageCustom from "../../component/widget/FastImageCustom";
import {Store} from "../../store";
import {KeyboardAwareScrollView} from "react-native-keyboard-aware-scroll-view";
import * as _ from "lodash";
import EmptyTip from "../../component/common/EmptyTip";
import {CheckBox} from "react-native-elements";

export interface productOrderItem {
    product: ProductModelExtraInfoInterface;
    count: number;
    maxCount: number;
    selectedSpecification: ProductSpecificationInterface;
}

interface RouterProps {
    params: {
        orderList: productOrderItem[]

    }
}

interface CheckBillState {
    selfTake: boolean;
    orderList: productOrderItem[]
}

interface CheckBillProps extends Store {
}

export default class CheckBillWrapper extends Component {
    onEnter(props: RouterProps) {
        const checkBill: CheckBill = this.refs.checkBill["wrappedInstance"];
        checkBill.onEnter(props);
    }

    render() {
        return <CheckBill ref={"checkBill"}/>
    }
}

@inject("product", "user", "address", "order")
@observer
class CheckBill extends Component<CheckBillProps, CheckBillState> {


    constructor(props) {
        super(props);
        this.state = {
            orderList: [],
            selfTake: false
        };
    }

    takeBySelf = (flag) => {
        this.setState({
            selfTake: flag
        });
    };

    componentDidMount() {
        afterAnimation(async () => {
            await this.props.address.getUserShippingAddress();

            if (this.addressIsEmpty) {
                alertProxy("提示", "请先补全收货地址!", [{
                    text: "知道了", onPress() {
                        Actions.push("AddressSetting");
                    }
                }])
            }
        });
    }

    onEnter(props: RouterProps) {
        this.setState(props.params)
    }

    createOrder = async () => {
        //TODO 默认为不自提
        await this.props.order.createOrder(this.state.orderList, +this.state.selfTake, this.totalPrice, this.canDeductionScore);
        global.showSuccess("订单创建成功！", 500, function () {
            Actions.PayWay();
        });
    };

    get addressIsEmpty() {
        return _.isEmpty(this.props.address.userAddress);
    }

    _renderAddress() {
        const {name, phone, addressDetail} = this.props.address.userAddress;
        return (
            <View style={[padding(17, 25), {marginTop: 8, backgroundColor: "#fff"}]}>
                <View>
                    <View style={[styles.flexDirectionRowNotFlex]}>
                        <Text style={CheckBillStyles.commonFont}>{name}</Text>
                        <Text style={[CheckBillStyles.commonFont, {marginLeft: 34}]}>{phone}</Text>
                    </View>
                    <Text style={{marginTop: 6, fontSize: 14, color: "#666666"}}>{addressDetail}</Text>
                </View>
            </View>
        )
    }

    updateOrderItemCount = (itemIndex: number) => {
        return (count: number) => {

            const orderList = this.state.orderList.map(function (item, index) {
                if (index === itemIndex) {
                    item.count = count;
                }
                return item;
            });
            this.setState({orderList})
        }
    };

    //总金额
    get totalPrice() {
        if (!this.state.orderList.length) return 0;
        const totalPrice = this.state.orderList.reduce((initVal: number, cur: productOrderItem) => {
            const price = this.computedProductPrice(cur);
            const curPrice = price * cur.count;
            return initVal + curPrice;
        }, 0);
        //总金额加邮费-积分抵扣的油费金额
        return totalPrice + (this.totalFare - this.canDeductionScore);
    }

    //运费  当为自提时运费为0
    get totalFare() {
        if (!this.state.orderList.length || this.state.selfTake) return 0;
        return this.state.orderList.reduce((initVal: number, cur: productOrderItem) => {
            const postagePrice = cur.product.postage * cur.count;
            return initVal + postagePrice;
        }, 0);
    }

    // get specialTotalFare(){
    //     if (!this.state.orderList.length) return 0;
    //     return this.state.orderList.reduce((initVal: number, cur: productOrderItem) => {
    //         if(!cur.product.special) return initVal;
    //         const postagePrice = cur.product.postage * cur.count;
    //         return initVal + postagePrice;
    //     }, 0);
    // }
    //是否含有特殊商品
    get hasSpecialProduct() {
        return this.state.orderList.some((order) => {
            return order.product.type === 1;
        })
    }

    //积分可以抵扣的运费
    // 1. 当为自提时 不可抵扣
    // 2. 当特殊商品是 可以透支抵扣
    get canDeductionScore() {
        if (!this.state.orderList.length || this.state.selfTake) return 0;
        const totalFare = this.totalFare;
        const userModel = this.props.user.user;
        //当用户积分大于运费 或者订单中含有特殊商品时  直接抵扣全部运费
        if (userModel.integral > totalFare || this.hasSpecialProduct) {
            return totalFare;
        } else {
            return userModel.integral < 0 ? 0 : userModel.integral;
        }
    }

    computedProductPrice(productItem) {
        const {selectedSpecification, product} = productItem;
        return selectedSpecification.id ? selectedSpecification.price : product.price;
    }


    _renderOrder() {
        const orderList = this.state.orderList;
        return (
            <View style={margin(8, 0)}>
                {orderList.map((item, index) => {
                    const {product = defaultObj, selectedSpecification = defaultObj, count,maxCount} = item;
                    const {name, imageUrl, infoImageUrl} = product;
                    const {name: sepcName} = selectedSpecification;
                    const price = this.computedProductPrice(item);
                    return (<View key={index} style={[styles.flexDirectionRowNotFlex, padding(15), {
                        backgroundColor: "#fff",
                        marginTop: 1
                    }]}>
                        <FastImageCustom source={{uri: getAssetUrl(infoImageUrl)}}
                                         resizeMode={"contain"}
                                         style={[rectWithSize(100), {marginRight: 15}]}/>
                        <View style={[styles.flex, styles.justifyBetween]}>
                            <Text style={CheckBillStyles.commonFont}>{name}</Text>
                            <View>
                                <Text style={{fontSize: 12, color: "#999999", marginBottom: 8}}
                                      numberOfLines={1}>{sepcName}</Text>
                                <Text style={[CheckBillStyles.commonFont, {color: "red"}]}>￥{price * count}</Text>
                            </View>
                        </View>
                        <Stepper updateCount={this.updateOrderItemCount(index)} count={count} maxCount={maxCount}
                                 style={{alignSelf: "flex-end"}}/>
                    </View>)
                })}
            </View>
        )
    }

    _renderMiscellaneous() {
        return (<View>
            <View style={CheckBillStyles.row}>
                <Text style={{fontSize: 14, color: "#333"}}>自提</Text>
                <CommonRadio size={20} onChecked={this.takeBySelf}/>
            </View><View style={CheckBillStyles.row}>
            <Text style={{fontSize: 14, color: "#333"}}>运费</Text>
            <Text style={{
                fontSize: 16,
                fontWeight: "bold",
                color: "#333"
            }}>{this.totalFare ? `￥${this.totalFare}` : '免费'}</Text>
        </View>
            <View style={CheckBillStyles.row}>
                <Text style={{fontSize: 14, color: "#333"}}>运费抵扣</Text>
                <View style={[styles.flexDirectionRowNotFlex, styles.centerH]}>
                    <Text style={{
                        color: "#629C36",
                        fontSize: 12,
                        marginRight: 15
                    }}>{this.canDeductionScore > 0 ? `会员积分抵扣 - ￥${this.canDeductionScore}` : '无'}</Text>
                    <AppIcon name={"youjiantou"} size={12} color={"#9D9D9D"}/>
                </View>
            </View>
            <View style={[CheckBillStyles.row, styles.justifyStart]}>
                <Text style={{color: "#333333", marginRight: 10}}>备注:</Text>
                <TextInput autoCorrect={true} autoCapitalize={"none"} underlineColorAndroid={"transparent"}
                           style={[padding(0), styles.flex]}
                           placeholder={"100字以内..."}
                           placeholderTextColor={"#999999"}/>
            </View>
        </View>)
    }

    _renderOrderDetails() {
        return (<View style={{marginTop: 8}}>
            <View style={CheckBillStyles.row}>
                <Text style={{fontSize: 14, color: "#333"}}>实付款</Text>
                <Text style={{fontSize: 16, fontWeight: "bold", color: "#333"}}>￥{toFixed(this.totalPrice, 2)}</Text>
            </View>
            <View style={CheckBillStyles.row}>
                <Text style={{fontSize: 14, color: "#333"}}>优惠</Text>
                <Text style={{
                    fontSize: 14,
                    color: "#333"
                }}>{this.canDeductionScore > 0 ? `￥${toFixed(this.canDeductionScore, 2)}` : "无"}</Text>
            </View>
        </View>)
    }

    _renderBottomBar() {
        return (<View
            style={[CheckBillStyles.bottomRow, CheckBillStyles.bottomBar, styles.justifyEnd]}>
            <View style={[styles.flexDirectionRowNotFlex]}>
                <Text style={{color: "#333333", fontSize: 14}}>合计：</Text>
                <Text style={{color: "#DB0000", fontSize: 14}}>￥{toFixed(this.totalPrice, 2)}</Text>
            </View>
            <TouchableOpacity onPress={this.createOrder} style={[styles.centered, padding(7, 44), {
                borderRadius: 3,
                marginLeft: 14,
                backgroundColor: "#629C36"
            }]}>
                <Text style={{fontSize: 16, color: "#FFFFFF"}}>付款</Text>
            </TouchableOpacity>
        </View>)
    }

    render() {
        return this.addressIsEmpty ? <EmptyTip style={{marginTop: 30}}/> : (
            <KeyboardAwareScrollView showsVerticalScrollIndicator={false} style={styles.flex} contentContainerStyle={CheckBillStyles.container}>
                {this._renderAddress()}
                {this._renderOrder()}
                {this._renderMiscellaneous()}
                {this._renderOrderDetails()}
                {this._renderBottomBar()}
            </KeyboardAwareScrollView>
        )
    }
}

const style: any = {
    container: {minHeight: HUNDRED_PERCENT, paddingBottom: 60},
    commonFont: {
        fontSize: 16,
        fontWeight: "bold",
        color: "#000"
    },
    row: {
        backgroundColor: "#fff",
        height: 46,
        marginTop: 1,
        paddingHorizontal: 25,
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between"
    },
};

const CheckBillStyles = StyleSheet.create({
    ...style,
    bottomRow: {
        backgroundColor: "#fff",
        marginTop: 1,
        paddingHorizontal: 18,
        flexDirection: "row",
        alignItems: "center",
    },
    bottomBar: {
        height: 50,
        position: "absolute",
        bottom: 0,
        left: 0,
        right: 0
    },
    innerRow: {
        ...style.row,
        marginTop: 0,
        height: null,
        paddingHorizontal: null,
        paddingVertical: 6
    }, containerRow: {
        ...style.row,
        height: null,
        flexDirection: "column",
        alignItems: null,
        justifyContent: null,
        paddingVertical: 3

    },
});
